package com.ruoyi.elebook.controller;

import com.itextpdf.text.DocumentException;
import com.ruoyi.common.core.utils.file.FileTypeUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.elebook.domain.BookElebook;
import com.ruoyi.elebook.domain.BookElebookVo;
import com.ruoyi.elebook.service.IBookElebookService;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 电子书Controller
 *
 * @author ruoyi
 * @date 2023-12-11
 */
@RestController
@RequestMapping("/elebook")
public class BookElebookController extends BaseController
{
    @Autowired
    private IBookElebookService bookElebookService;
    /**
     * 资源映射路径 前缀
     */
    @Value("${url.path}")
    public String localFilePrefix;
    private final ExecutorService executor = Executors.newFixedThreadPool(10);

    private final CopyOnWriteArrayList<SseEmitter> emitters = new CopyOnWriteArrayList<>();
    /**
     * 查询电子书列表
     */
    @RequiresPermissions("elebook:elebook:list")
    @GetMapping("/list")
    public TableDataInfo list(BookElebook bookElebook)
    {
        startPage();
        List<BookElebook> list = bookElebookService.selectBookElebookList(bookElebook);
        for(BookElebook book : list){
            book.setFilePages(this.bookElebookService.selectPageByElebookId(book.getId()));
        }
        return getDataTable(list);
    }

    /**
     * 导出电子书列表
     */
    @RequiresPermissions("elebook:elebook:export")
    @Log(title = "电子书", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BookElebook bookElebook)
    {
        List<BookElebook> list = bookElebookService.selectBookElebookList(bookElebook);
        ExcelUtil<BookElebook> util = new ExcelUtil<BookElebook>(BookElebook.class);
        util.exportExcel(response, list, "电子书数据");
    }

    /**
     * 获取电子书详细信息
     */
    @RequiresPermissions("elebook:elebook:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bookElebookService.selectBookElebookById(id));
    }

    /**
     * 新增电子书
     */
    @RequiresPermissions("elebook:elebook:add")
    @Log(title = "电子书", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BookElebook bookElebook)
    {
         String bookName = toPinYin(bookElebook.getName());
        int length = 10; // 指定字符串长度
        String characters = "abcdefghijklmnopqrstuvwxyz"; // 英文字母字符集
        StringBuilder sb = new StringBuilder(length);
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            char randomChar = characters.charAt(index);
            sb.append(randomChar);
        }
        String randomString = sb.toString();
        bookElebook.setAccessUrl(localFilePrefix+"/"+"read"+"/"+bookName+"/"+randomString);
        return toAjax(bookElebookService.insertBookElebook(bookElebook));
    }

    /**
     * 修改电子书
     */
    @RequiresPermissions("elebook:elebook:edit")
    @Log(title = "电子书", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BookElebook bookElebook)
    {
        String bookName = toPinYin(bookElebook.getName());
        int length = 10; // 指定字符串长度
        String characters = "abcdefghijklmnopqrstuvwxyz"; // 英文字母字符集
        StringBuilder sb = new StringBuilder(length);
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            char randomChar = characters.charAt(index);
            sb.append(randomChar);
        }
        String randomString = sb.toString();
        bookElebook.setAccessUrl(localFilePrefix+"/"+"read"+"/"+bookName+"/"+randomString);
        return toAjax(bookElebookService.updateBookElebook(bookElebook));
    }

    /**
     * 删除电子书
     */
    @RequiresPermissions("elebook:elebook:remove")
    @Log(title = "电子书", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(bookElebookService.deleteBookElebookByIds(ids));
    }


    /**
     * 文件上传解析
     */
    @RequiresPermissions("elebook:elebook:upload")
    @Log(title = "电子书")
    @RequestMapping("/file/upload")
    public AjaxResult fileUpload(BookElebookVo bookElebookVo) throws IOException, DocumentException {
        try {
            if (!bookElebookVo.getFile().isEmpty())
            {
                String extension = FileTypeUtils.getExtension(bookElebookVo.getFile());
                if(extension.equals("pdf")){
                    if(bookElebookService.insertFile(bookElebookVo) == 1){
                        return success("上传成功");
                    }else {
                        return error("上传失败");
                    }
                }else{
                    return error("文件格式不正确");
                }
            }else{
                return error("文件为null");
            }
        }catch (Exception e){
            throw  e;
        }

    }

    /**
     * 修改电子书
     */
    @RequiresPermissions("elebook:elebook:edit")
    @Log(title = "电子书")
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody BookElebook bookElebook)
    {
        bookElebook.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(bookElebookService.updateBookElebook(bookElebook));
    }




    public static String toPinYin(String chinese) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); // 不带声调

        StringBuilder resultBuilder = new StringBuilder();

        for (char c : chinese.toCharArray()) {
            if (Character.toString(c).matches("[\\u4e00-\\u9fa5]+")) {
                try {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    resultBuilder.append(temp[0]);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                resultBuilder.append(c);
            }
        }
        return resultBuilder.toString();
    }
}
